/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app.controller.util;

import app.entity.Mail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

/**
 *
 * @author Song Lam
 */
public class SendMail {

    

    public int sendMail(Mail m) {
        try {            
            /*
            this.to = "dtbinhqb@gmail.com";            
            
            
            subject = "subject";
            message = "message";
            
            */
            m.setSubject("Recover Password");
            m.setFrom("Java.Mail.CA@gmail.com");
            m.setSmtpServ("smtp.gmail.com");
            Properties props = System.getProperties();
            // -- Attaching to default Session, or we could start a new one --
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", m.getSmtpServ());
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SendMail.SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            // -- Create a new message --
            Message msg = new MimeMessage(session);
            // -- Set the FROM and TO fields --
            msg.setFrom(new InternetAddress(m.getFrom()));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(m.getTo(), false));
            msg.setSubject(m.getSubject());
            msg.setText(m.getMessage());
            // -- Set some other header information --
            msg.setHeader("MyMail", "Mr. XYZ");
            msg.setSentDate(new Date());
            // -- Send the message --
            Transport.send(msg);
            
            return 0;
        } catch (Exception ex) {
            ex.printStackTrace();            
            return -1;
        }
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = "sendmail.jsf@gmail.com";           // specify your email id here (sender's email id)
            String password = "sendmail.jsf";                                      // specify your password here
            return new PasswordAuthentication(username, password);
        }
    }
}
